package com.meicunbing.viberplugin.com;

import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.util.Log;

public class Weather {
	/*
	 * http://61.4.185.48:81/g/ (根据IP查询城市ID)
	 * http://m.weather.com.cn/data/101110101.html（六天预报）
	 * http://www.weather.com.cn/data/sk/101110101.html（实时天气信息）
	 */
	static String fUri = "http://m.weather.com.cn/data/";
	static String nUri = "http://www.weather.com.cn/data/sk/";
	private String cityCode = "";
	private String fUrl = "";

	public String getfUrl() {
		if (fUrl.equals("".toString())) {
			setfUrl(fUri + cityCode + ".html");
		}
		return fUrl;
	}

	public void setfUrl(String fUrl) {
		this.fUrl = fUrl;
	}

	public String getnUrl() {
		if (nUrl.equals("".toString())) {
			setnUrl(nUri + cityCode + ".html");
		}
		return nUrl;
	}

	public void setnUrl(String nUrl) {
		this.nUrl = nUrl;
	}

	private String nUrl = "";

	public String getCityCode() {
		return cityCode;
	}

	public void setCityCode(String cityCode) {
		this.cityCode = cityCode;
	}

	public JSONObject convertFromJsonStr(String Json) {

		try {
			JSONTokener jsonParser = new JSONTokener(Json);
			JSONObject weather = ((JSONObject) jsonParser.nextValue())
					.getJSONObject("weatherinfo");
			return weather;
		} catch (JSONException ex) {
			// 异常处理代码
		}
		return null;
	}

	public JSONObject getfWeather() {
		return getWeather(getfUrl());
	}

	public JSONObject getnWeather() {
		return getWeather(getnUrl());
	}

	public JSONObject getWeather(String Url) {
		Log.i("URL", Url);
		// 第1步：创建HttpGet对象
		HttpGet httpGet = new HttpGet(Url);

		// 第2步：使用execute方法发送HTTP GET请求，并返回HttpResponse对象
		HttpResponse httpResponse = null;
		try {
			httpResponse = new DefaultHttpClient().execute(httpGet);
		} catch (ClientProtocolException e1) {
			Log.e("HTTP", e1.getMessage());
			//e1.printStackTrace();
			return null;
		} catch (IOException e1) {
			Log.e("HTTP", e1.getMessage());
			//e1.printStackTrace();
			return null;
		}

		// 判断请求响应状态码，状态码为200表示服务端成功响应了客户端的请求
		if (httpResponse != null &&httpResponse.getStatusLine().getStatusCode() == 200) {
			// 第3步：使用getEntity方法获得返回结果
			String result;
			try {
				result = EntityUtils.toString(httpResponse.getEntity());
				Log.i("httpResponse", result);
			} catch (ParseException e) {
				//e.printStackTrace();
				return null;
			} catch (IOException e) {
				//e.printStackTrace();
				return null;
			}
			return convertFromJsonStr(result);

		}
		return null;
	}
}
